/*
 * Copyright 2010 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.androidpn.sdk;

import java.net.URLDecoder;
import java.util.ArrayList;
import org.jivesoftware.smack.PacketListener;
import org.jivesoftware.smack.packet.Packet;
import com.eipc.MainActivity;
import com.eipc.model.Consult;
import com.eipc.model.ImportNotice;
import com.eipc.model.Match;
import com.eipc.model.Score;
import com.eipc.model.Weather;
import com.eipc.util.DataParse;
import android.content.Intent;
import android.util.Log;

/** 
 * Class desciption here.
 *
 * @author Sehwan Noh (sehnoh@gmail.com)
 */
public class NotificationPacketListener implements PacketListener {

    private static final String LOGTAG = NotificationPacketListener.class.getName();

    private final XmppManager xmppManager;

    public NotificationPacketListener(XmppManager xmppManager) {
        this.xmppManager = xmppManager;
    }

    @Override
    public void processPacket(Packet packet){
    	//-1异常 0刷新 1重要通知 2我要报告 3工作汇报 4天气预报 5观众意见 6签表 7每日对阵 8noticeMaxID 10mach 11score
        int model = -1;
        //方式 0GET 1POST
        int sendType = 1;
        Log.e(LOGTAG, "NotificationPacketListener.processPacket()...");
        Log.e(LOGTAG, "packet.toXML()=" + packet.toXML());

        if (packet instanceof NotificationIQ){
            NotificationIQ notification = (NotificationIQ) packet;
            if (notification.getChildElementXML().contains("androidpn:iq:notification")){
                String notificationId = notification.getId();
                String notificationApiKey = notification.getApiKey();
                String notificationTitle = notification.getTitle();
                
                if(notificationTitle!=null&&!"".equals(notificationTitle)){
                	String[] ms = notificationTitle.split("_");
                	if(ms.length == 2){
                		try{model = Integer.valueOf(ms[0]).intValue();}catch(Exception e){model = -1;}
                		try{sendType = Integer.valueOf(ms[1]).intValue();}catch(Exception e){sendType = 1;}
                	}
                }
                
                String notificationMessage;
                if(sendType == 0){
                	notificationMessage = URLDecoder.decode(notification.getMessage());
                }else{
                	notificationMessage = notification.getMessage();
                }
                
                String notificationTicker = notification.getTicker();
                String notificationUrl = notification.getUrl();

                Intent intent = new Intent("org.androidpn.sdk.SHOW_NOTIFICATION");
                intent.putExtra("NOTIFICATION_ID", notificationId);
                intent.putExtra("NOTIFICATION_API_KEY", notificationApiKey);
                intent.putExtra("NOTIFICATION_TITLE", notificationTitle);
                intent.putExtra("NOTIFICATION_MESSAGE", notificationMessage);
                intent.putExtra("NOTIFICATION_TICKER", notificationTicker);
                intent.putExtra("NOTIFICATION_URL", notificationUrl);
                
                Log.e("--------notificationId----------",notificationId);
                Log.e("--------notificationApiKey----------",notificationApiKey);
                Log.e("--------notificationTitle----------",notificationTitle);
                Log.e("--------notificationMessage----------",notificationMessage);
                Log.e("--------notificationTicker----------",notificationTicker);
                Log.e("--------notificationUrl----------",notificationUrl);
                Log.e("--------model----------",""+model);
                
                switch(model){
                	case 0:doRefresh();break;
                	case 1:
                	case 2:
                	case 3:doNotice(notificationMessage);break;
                	case 4:doWeather(notificationMessage);break;
                	case 5:doConsult(notificationMessage);break;
                	case 6:break;
                	case 7:break;
                	case 8:xmppManager.mDBHelper.updateMaxId(notificationMessage);break;
                	case 10:doMach(notificationMessage);break;
                	case 11:doScore(notificationMessage);break;
                	default:Log.e(LOGTAG,"Push Error : model = "+model);break;
                }
            }
        }
    }

    public void doRefresh(){
    	Intent i = new Intent("action.push.finish");
    	XmppManager.getContext(xmppManager).sendBroadcast(i);
    }
    
    public void doNotice(String msg){
    	ImportNotice in =  DataParse.ParseImportNotice(msg); 
    	if(in!=null){
    		ArrayList<ImportNotice> inList = new ArrayList<ImportNotice>();
    		inList.add(in);
    		xmppManager.mDBHelper.insertImportNotice(inList);
    		Intent i = new Intent(MainActivity.ACTION_POPUP_MESSAGE);
    		i.putExtra("id", in.noticeId);
    		XmppManager.uploadNotification(XmppManager.getContext(xmppManager),true);
    		XmppManager.getContext(xmppManager).sendBroadcast(i);
    	}else{
    		Log.e(LOGTAG,"ParseImportNotice Error : notificationMessage = " + msg);
    	}
    }
        
    public void doScore(String msg){
    	Score s = DataParse.ParseScore(msg);
    	Log.e("-------doScore---------",String.valueOf(s));
    	if(s!=null){
    		ArrayList<Score> list = new ArrayList<Score>();
    		list.add(s);
    		xmppManager.mDBHelper.insertScore(list);
    	}
    }
    
    public void doMach(String msg){
    	Match m = DataParse.ParseMatch(msg);
    	Log.e("-------doMach---------",String.valueOf(m));
    	if(m!=null){
    		ArrayList<Match> list = new ArrayList<Match>();
    		list.add(m);
    		xmppManager.mDBHelper.insertMatch(list);
    	}
    }
    
    public void doConsult(String msg){
    	Consult con =  DataParse.ParseConsult(msg); 
    	Log.e("-------doConsult---------",String.valueOf(con));
    	if(con!=null){
    		xmppManager.mDBHelper.saveConsult(con);
    	}
    }
    
    public void doWeather(String msg){
    	Weather we =  DataParse.ParseWeather(msg); 
        if(we!=null){
        	xmppManager.mDBHelper.saveWeather(we);
        }
    }

}
